
const path = require('path')
const shell = require('shelljs')
const print = require('../../lib/print')
const git = require('../../lib/git')

const MAINAPP_DIR = '/Users/caoyq/Work/微盟/MWMainAPP'
// 
const allBusiness = [ 'XYPublicClasses', 
                      'XYECommerce-Goods', 
                      'XYECommerce-Data', 
                      'XYECommerce-GroupBuy', 
                      'XYECommerce-Market', 
                      'XYECommerce-Customer', 
                      'XYECommerce-Public', 
                      'XYECommerce-Transaction', 
                      'XYECommerce', 
                      'XYMainApp' ]

module.exports = function () {
    for (let index in allBusiness) {
        let business = allBusiness[index]
        let businessPath = `${MAINAPP_DIR}/${business}`
        //
        shell.cd(businessPath)
        if (git.isMasterBranch() !== true) {
            handleOtherBranch()
        }
        handleMasterBranch()
        print.successLog(`${business} 库已拉取最新 master 分支`)
    }
}

// 处于 master 分支：清空当前工作区，并拉取最新代码
function handleMasterBranch() {
    // 清空已 add 内容，回退到工作区
    shell.exec('git reset .')
    // 清空已修改内容
    shell.exec('git checkout .')
    // 清空新建文件等
    shell.exec('git clean -f')
    // 拉取最新
    shell.exec('git pull')
}

// 非 master 分支：本地修改内容提交保存，再切换到 master
function handleOtherBranch() {
    if (git.isBranchChanged()) {  //  分支有改动先提交
        shell.exec('git add *')
        shell.exec("git commit -m '由于需自动切换到 master 分支，当前分支已修改内容进行临时提交~~' ")
    }
    shell.exec('git checkout master')
}